import Base from '@/common/cmdBase/cmdBase';
import { useRenderStore } from '@/common/store';
import { NMMeshBaseCommand } from '@/common/types';
import { nmAppErrorLog, nmAppLog } from '@/common/utils';
import i18n from '@/common/utils/i18next';
import { mesh } from '@/domain';
import { PointsEntity, THREE } from '@amcax/web-render';
import { IChangeEvent } from '@rjsf/core';
import { CmdDialogForm, ManagerId } from 'nextcae-base';
import { useState } from 'react';
import { schema, uiSchema } from './data';
import { MeshDialogProps } from './type';

// 种子
function SeedEditDialog({ title, onClose }: MeshDialogProps) {
  const { mainRenderer } = useRenderStore();
  // 记录当前高亮是哪个字段
  const [formData, setFormData] = useState<any>();

  const renderPoints = (points: THREE.Vector3Tuple[]) => {
    const dxid = 'seed-edit-points'; // 固定的id，用于创建和删除
    const assisMgr = mainRenderer.getEntityManager(ManagerId.Assis);
    // 暂时 直接清除老的，然后插入新的；会出现闪烁，待优化
    assisMgr.removeEntity([dxid]);
    const length = points.length;
    // 创建点的Entity（多个点在一个Entity中）
    const ids = new Uint32Array(length); // id数组
    const position = new Float32Array(length * 3); // 坐标[x,y,z,x,y,z]，所以长度是3*length
    for (let i = 0; i < length; i++) {
      ids[0] = i;
      position.set(points[i], i * 3);
    }
    const pointEntity = new PointsEntity(dxid, ids, position);
    assisMgr.addEntity(pointEntity);
  };
  const handleSubmit = async (data) => {
    if (data) {
      setFormData(data);
      try {
        let params: any = {};
        if (data.Tabs === 'Number') {
          params = {
            Method: data.Tabs, // Number/Size/Align
            Source: 'edge',
            Biasing: data.DistributionOptions.biasing, // None/Linear/Exponential/BellCurve
            Factor: data.DistributionOptions.factor,
            Number: data.DistributionOptions.number,
            ReverseDirection: data.reverseDirection, // 是否反转
            SelectedEntities: data.Selection.source?.map(Base.makeIdNew), // 选取的边id数组
          };
          (params.Factor === '' || params.Factor === undefined) &&
            delete params.Factor;
        } else if (data.Tabs === 'Size') {
          params = {
            Method: data.Tabs, // Number/Size/Align
            Source: 'edge', // 拾取类型
            Biasing: data.DistributionOptions.biasing, // None/Linear/Exponential/BellCurve
            Factor: data.DistributionOptions.factor,
            Size: data.DistributionOptions.size,
            StartSize: data.DistributionOptions.startSize,
            EndSize: data.DistributionOptions.endSize,
            ReverseDirection: data.reverseDirection, // 是否反转
            SelectedEntities: data.Selection.source?.map(Base.makeIdNew), // 选取的边id数组
          };
          (params.Factor === '' || params.Factor === undefined) &&
            delete params.Factor;
          (params.Size === '' || params.Size === undefined) &&
            delete params.Size;
          (params.StartSize === '' || params.StartSize === undefined) &&
            delete params.StartSize;
          (params.EndSize === '' || params.EndSize === undefined) &&
            delete params.EndSize;
        } else if (data.Tabs === 'Align') {
          params = {
            Method: data.Tabs, // Number/Size/Align
            Source: data.Selection.source?.map(Base.makeIdNew),
            Target: data.Selection.target?.map(Base.makeIdNew),
          };
        }
        const points = await mesh.seed(params);
        renderPoints(points);
        setFormData({ ...formData, Selection: { Source: [], Target: [] } });
      } catch (error) {
        nmAppErrorLog('cmd-seed-edit', 'onSubmit', error);
      }
    }
  };
  const handleChange = (data: IChangeEvent, id) => {
    nmAppLog('handleChange:', data, id);
    if (data.formData) {
      setFormData({
        ...data.formData,
      });
    }
  };
  const isFormDataValid = () => {
    let valid = formData?.Selection?.source?.length > 0;
    if (formData?.Tabs === 'Align') {
      valid = valid && formData?.Selection?.target?.length > 0;
    }
    return valid;
  };
  return (
    <CmdDialogForm
      onClose={onClose}
      onSubmit={handleSubmit}
      formData={formData}
      schema={schema}
      extraUiSchema={uiSchema}
      title={title}
      onChange={handleChange}
      isFormDataValid={isFormDataValid()}
      titleIcon={'commands/mesh/lineMesh'}
    />
  );
}
// 种子
export const cmdSeedEdit: NMMeshBaseCommand = {
  id: 'cmdSeedEdit',
  icon: 'commands/mesh/node-distribution',
  label: 'command.mesh.seedEdit',
  create: (label: string, onClose: () => void, props) => (
    <SeedEditDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
